/**
 * @page: 角色管理页面
 * @author:yangshaopeng
 */
import { useEffect, useState, useMemo } from 'react';
import OperaBtnRender from '@/components/OperaBtnRender';
import TableRender from '@/components/TableRender';
import SetRoleAuthorize from './component/SetRoleAuthorize.jsx';
import { queryPage, deleteRole } from './service';
import { getColumns } from './config/columns.jsx';
import { message } from 'antd';

const RoleComponent = () => {

  const [data, setData] = useState([]);
  const [item, setItem] = useState({});
  const [visible, setVisible] = useState(false);
  const [pages, setPages] = useState({
    current: 1,
    total: 0,
    pageSize: 10,
  })

  useEffect(() => {
    getTableList();
  }, [pages.current, pages.pageSize])

  //获取角色列表
  const getTableList = async (current = undefined, size = undefined) => {
    START_LOADING();
    const { data, success } = await queryPage({
      current: current ? current : pages.current,
      size: size ? size : pages.pageSize,
    })
    END_LOADING();
    if (success) {
      const { records, total } = data;
      setPages({ ...pages, total });
      setData(records);
    } 
  }

  const handleDelete = async (record) => {
    START_LOADING();
    const { success } = await deleteRole({
      ids: record.id
    })
    END_LOADING();
    if (success) {
      message.success('删除成功！');
      getTableList();
    }
  }

  //添加/编辑角色
  const handleAddRole = (type = 2, obj = {}) => {
    if (type == 1) {
      setItem(obj);
      setVisible(true);
    } else {
      setItem({});
      setVisible(true);
    }
  }

  //点击编辑和删除
  const handleOpera = (type, record) => {
    if (type == 'edit') {
      handleAddRole(1, record);
    } else {
      handleDelete(record);
    }
  }

  //表格列
  const columns = useMemo(() => {
    return getColumns({ handleOpera })
  }, [])

  //表格组件
  const TableRenderProps = {
    data,
    columns,
    style: {
      height: `calc(100vh - 208px)`
    },
    pageConfig: {
      pages,
      handlePageSize(page, size) {
        setPages({
          ...pages,
          current: page,
          pageSize: size
        });
      }
    }
  }

  const SetRoleAuthorizeProps = {
    item,
    visible,
    handleOk() {
      getTableList();
    },
    handleCancel() {
      setItem({});
      setVisible(false);
    }
  }

  //操作按钮
  const btnArr = [
    { elType: 'button', text: '添加角色', onClick: handleAddRole }
  ]

  return (
    <div className='global-page-wrap'>
      <OperaBtnRender style={{ marginBottom: '12px' }} btnArr={btnArr} />
      <TableRender {...TableRenderProps} />
      { visible && <SetRoleAuthorize {...SetRoleAuthorizeProps} /> }
    </div>
  );
};

export default RoleComponent;
